{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime, timedelta  \n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "\n",
    "#======下面行解决DataFrame打印时表头与数据不对齐的问题。====\n",
    "pd.set_option('display.unicode.east_asian_width', True)\n",
    "\n",
    "# 获取平安银行（000001）的日K线数据\n",
    "df = ak.stock_zh_a_hist(symbol=\"000001\", adjust=\"qfq\")\n",
    "# 打印结果\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 日期列转换时间类型\n",
    "df['日期'] = pd.to_datetime(df['日期'])\n",
    "df.日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义开始和结束日期  \n",
    "start_date = '2023-01-01'  # 例如：2023年1月1日  \n",
    "end_date = '2023-06-30'   # 例如：2023年6月30日  \n",
    "  \n",
    "# 将字符串转换为datetime对象（如果它们不是的话）  \n",
    "start_date = datetime.strptime(start_date, '%Y-%m-%d')  \n",
    "end_date = datetime.strptime(end_date, '%Y-%m-%d')  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用pandas的.loc[]方法来筛选时间范围内的数据  \n",
    "# 注意：这里假设'date'列是DataFrame的索引，如果不是，你可以使用.set_index('date')来设置  \n",
    "# 如果'date'列不是索引，但仍然是一个列，你可以这样做：  \n",
    "# df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]  \n",
    "  \n",
    "# 如果'date'列是索引：  \n",
    "mask = (df.日期 >= start_date) & (df.日期 <= end_date)  \n",
    "df = df.loc[mask]  \n",
    "\n",
    "# 现在filtered_df包含了指定时间范围内的数据  \n",
    "print(df) \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.index = pd.to_datetime(df['日期'])\n",
    "df"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
